package org.scboy.rbac.detect;

import java.util.Date;
import java.util.List;

import org.scboy.common.cache.SystemConfig;
import org.scboy.coobi.sql.factory.EntityFactory;
import org.scboy.rbac.dao.RbacLoginStateDao;
import org.scboy.rbac.service.LoginSessionService;
import org.scboy.utils.entitys.coobi.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import cn.hutool.core.convert.Convert;

/**
 * 检测登录状态
 */
@Configuration
@EnableScheduling
public class LoginStateDetect {
	

	@Autowired
	LoginSessionService loginSession;

	@Autowired
	SystemConfig config;

	@Autowired
	EntityFactory factory;
	
	/**
	 * 每分钟检查登录状态
	 */
	@Scheduled(cron = "0 0/1 * * * ?")
	private void detect() {
		
		RbacLoginStateDao dao=factory.getDao(RbacLoginStateDao.class);

		//登录保持时长
		Integer checkLength=Convert.toInt(config.getConfig("CHECK_LENGTH"));

		//登陆超时时间
		Integer loginOutTime=Convert.toInt(config.getConfig("LOGIN_OUT_TIME"));
		
		if(checkLength > 0 || loginOutTime > 0) {
			
			List<Model> list=dao.select(Model.create().add("sessionState", 0));
			
			for (Model state : list) {
				
				String sessionId=state.getString("sessionId");
				
				if(checkLength > 0) {
					long timeTick=state.getDate("loginTime").getTime();
					if(timeTick+checkLength * 60000 < new Date().getTime()){
						loginSession.loginOut(sessionId, 4);
						continue;
					}
				}
				
				if(loginOutTime > 0) {
					long timeTick=state.getDate("lastTime").getTime();
					if(timeTick + loginOutTime * 60000 < new Date().getTime()){
						loginSession.loginOut(sessionId, 4);
						continue;
					}
				}
			}
		}
	}
}
